<?php
/**
 * Created by PhpStorm.
 * User: yulin
 * Date: 2018-7-9
 * Time: 16:03
 */
namespace app\open\model;

use traits\model\SoftDelete;
use app\open\filter;
use app\base\exception\RecordNotFoundException;
use think\Db;
use think\exception\DbException;
class Car extends Common
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $autoWriteTimestamp = true;

    //区域
    public function area() {
        return $this->hasOne('Area','area_id','area_id','','left')->setEagerlyType(0);
    }
    //业务类型
    public function cartype() {
        return $this->hasOne('CarType','car_type_id','car_type_id','','left')->setEagerlyType(0);
    }
    //所属公司
    public function company() {
        return $this->hasOne('Company','company_id','company_id','','left')->setEagerlyType(0);
    }
    //委托公司
    public function entrust() {
        return $this->hasOne('Company','company_id','entrust_company_id','','left')->setEagerlyType(0);
    }
    //品牌
    public function brand() {
        return $this->hasOne('CarBrand','car_brand_id','car_brand_id','','left')->setEagerlyType(0);
    }
    //品牌
    public function model() {
        return $this->hasOne('CarBrand','car_brand_id','car_model_id','','left')->setEagerlyType(0);
    }
    //series
    public function series() {
        return $this->hasOne('CarBrand','car_brand_id','car_series_id','','left')->setEagerlyType(0);
    }
    //company_strength
    public function strength() {
        return $this->hasOne('CompanyStrength','id','company_strength_id','','left')->setEagerlyType(0);
    }

    /**
     * 新增或者编辑车辆
     * @param $params
     * @return $this|false|int
     * @throws RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function createOrUpdate($params) {
        $session = (new User())->getLoginUser();
        if(isset($params['car_id'])) {
            $where = ['car_id' => $params['car_id']];
            $buildQuery = function($query) use ($where) {
                self::authCompanyQuery($query, $where, 'a.company_id');
            };

            $car = self::get($buildQuery);
            if(!$car) {
                throw new RecordNotFoundException();
            }
        }elseif(!self::isSuperAdmin($session) && $session['user']['company_id']) {
            $params['company_id'] = $session['user']['company_id'];
        }

        // 验证单位是否存在
        $this->addRelativeFields( $params, 'app\adminapi\model\Company', $params['company_id'],  [], '关联单位不存在');

        if(isset($params['car_id'])) {
            return $this->isUpdate(true)->save($params);
        }

        $this->data($params)->save();

        return $this;
    }

    /**
     * 车辆列表
     * @param string $fields
     * @param array $where
     * @param int $page
     * @param int $num
     * @return array
     */
    public function carLlist($fields='*',$where=[],$page=1,$num=10){
        $filter          = new filter\CarList();
        $filter->analyzeField();
        list(,$msg)      = $filter->checkField($fields);
        list(,$whereMsg) = $filter->checkWhere($where);
        $data['note'] = "查询条件json输入格式如{'passenger_id':['in','6,7,8,9,10,11,12'],'passenger_name':['like','%王%']}";

        $buildQuery = function($query) use ($whereMsg) {
            self::authCompanyQuery($query, $whereMsg, 'a.company_id');
        };

        try{
            $data['data'] = $this->alias('a')
                ->join('car_type b','a.car_type_id = b.car_type_id','left')
                ->join('company c','a.company_id = c.company_id','left')
                ->join('car_brand d','a.car_brand_id = d.car_brand_id','left')
                ->join('car_brand e','a.car_model_id = e.car_brand_id','left')
                ->join('car_brand f','a.car_series_id = f.car_brand_id','left')
                ->join('car_insure g','a.car_id = g.car_id','left')
                ->where('g.policy_type',1)
                ->join('car_insure h','a.car_id = h.car_id','left')
                ->where('h.policy_type',2)
                ->field($msg)
                ->where($buildQuery)
                ->page($page,$num)
                ->order('a.car_id desc')
                ->select();
        }catch (DbException $e){
            abort(0,$e->getMessage());
        }
        $data['count'] = $this->alias('a')
            ->join('car_type b','a.car_type_id = b.car_type_id','left')
            ->join('company c','a.company_id = c.company_id','left')
            ->join('car_brand d','a.car_brand_id = d.car_brand_id','left')
            ->where($buildQuery)
            ->count();
        $data['data']        = $filter->checkData($data['data']);
        $data['description'] = $filter->title;
        $data['fields']      = $filter->fieldTitle;
        return [1,$data];
    }
}